import os


def ensure_directory(path):
    """检查并新建文件夹

    Args:
        path (str): 文件夹路径
    """
    if not os.path.exists(path):
        os.makedirs(path)


def get_full_path_for_module(module):
    """获取模块的全路径

    Args:
        module (module对象): 模块对象

    Returns:
        str: 模块对象对应全路径信息
    """
    path = []
    current_module = module
    while current_module:
        path.append(current_module.number.lower())
        current_module = current_module.parent
    return os.path.join(*reversed(path))


def write_content_to_file(filename, content):
    """向文件中写入内容

    Args:
        filename (str): 文件路径
        content (str): 文件内容
    """
    with open(filename, "w", encoding='utf-8') as file:
        file.write(content)


def read_content_from_file(filename):
    """从文件读取内容

    Args:
        filename (str): 文件路径
    """
    with open(filename, "r", encoding='utf-8') as file:
        content = file.read()
        return content


def build_pytest_project(local_path, testcases):
    """根据选择的用例信息，在本地生成pytest测试项目

    Args:
        local_path (str): 本地存放路径（临时）
        testcases (list): JobLog列表
    """
    for testcase in testcases:
        # 获取父级产品和模块
        product = testcase.product
        module = testcase.module

        # 创建产品、模块和测试用例的路径
        product_path = os.path.join(local_path, product.number.lower())
        module_path = os.path.join(
            product_path, get_full_path_for_module(module))

        # 确保目录存在
        ensure_directory(product_path)
        ensure_directory(module_path)

        main_script_content = """import yuantest

def main():
    # 执行当前目录文件夹下的所有测试用例
    # 使用 -v 参数使输出更加详终，使用 -s 参数允许打印输出
    yuantest.main(['-vs', '.'])

    if __name__ == '__main__':
        main()
        """

        # 写入各自的.py文件
        write_content_to_file(
            os.path.join(product_path, "main.py"),
            product.script or main_script_content,
        )
        write_content_to_file(
            os.path.join(module_path, "conftest.py"),
            module.script or "# Empty module script\n",
        )
        (
            write_content_to_file(
                os.path.join(
                    module_path, f"{testcase.number.lower()}.py"), testcase.script
            )
            if testcase.script
            else None
        )


def load_pytest_project(local_path, product, module, testcase):
    for root, dirs, files in os.walk(local_path):
        for file in files:
            model = testcase
            filename, _ = os.path.splitext(file)
            number = os.path.basename(root).upper()

            if (filename == 'main'):
                model = product
            elif (filename == 'conftest'):
                model = module
            else:
                number, _ = os.path.splitext(
                    os.path.basename(os.path.join(root, file)))
                number = number.upper()
            model.objects.filter(number=number).update(
                script=read_content_from_file(os.path.join(root, file)))
